/** @file

Copyright (c) 2006-2023, Kunlun BIOS, Kunlun Technology (Beijing) Co., Ltd.. All
Rights Reserved.

You may not reproduce, distribute, publish, display, perform, modify, adapt,
transmit, broadcast, present, recite, release, license or otherwise exploit
any part of this publication in any form, by any means, without the prior
written permission of Kunlun Technology (Beijing) Co., Ltd..

Module Name:


Abstract:


Revision History:

**/

#include <Uefi.h>
#include <Base.h>
#include <Library/BaseLib.h>
#include <Library/PrintLib.h>
#include <Library/DebugLib.h>
#include <Library/PcdLib.h>
#include <Library/FlashLib.h>
#include <Library/BaseMemoryLib.h>
#include <FlashRetainDefinitions.h>
#include <BiosGpnvData.h>

#define KL_RETAIN_SPACE_OFFSET    PcdGetEx64(&gPhytiumPlatformTokenSpaceGuid, PcdKlRetainSpaceOffsetEx) + PcdGetEx64(&gPhytiumPlatformTokenSpaceGuid, PcdFdBaseAddressEx)
#define KL_RETAIN_SPACE_SIZE      PcdGetEx32(&gPhytiumPlatformTokenSpaceGuid, PcdKlRetainSpaceSizeEx)

UINTN
GetRetainDataSize()
{
  UINT32      DataSize;
  UINT32      SectorNum;

  SectorNum = (sizeof(KL_FLASH_RETAIN_SPACE_DEFINE) / BLKSIZE64) + 1;
  DataSize = SectorNum * BLKSIZE64;

  if (DataSize > KL_RETAIN_SPACE_SIZE) {
    DataSize = KL_RETAIN_SPACE_SIZE;
  }

  return DataSize;
}


EFI_STATUS
GetRetainData (
  IN   UINTN    ByteCount,
  OUT  UINT8    *DataBuffer
  )
{
  UINTN       BaseAddr;

  BaseAddr = KL_RETAIN_SPACE_OFFSET;
  //FlashRead(BaseAddr, DataBuffer, ByteCount);
  CopyMem (DataBuffer, (VOID *)((UINTN)BaseAddr), ByteCount);

  if (ReadUnaligned64 ((UINTN *)DataBuffer) != EFI_KUNLUN_RETAIN_SPACE_SIGNATURE) {
    return EFI_NOT_FOUND;
  }

  return EFI_SUCCESS;
}


EFI_STATUS
SetRetainData (
  IN  UINTN    ByteCount,
  IN  UINT8    *DataBuffer
  )
{
  UINTN       BaseAddr;

  BaseAddr = KL_RETAIN_SPACE_OFFSET;

  FlashErase(BaseAddr);
  FlashWrite(DataBuffer, (UINT8 *)BaseAddr, ByteCount / 4);

  return EFI_SUCCESS;
}

